Indentation Style
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, an indentation style is a convention governing the
indentation __FORCETOC__ In the written form of many languages, an indentation or indent is an empty space at the beginning of a line to signal the start of a new paragraph. Many computer languages have adopted this technique to designate "paragraphs" or o ...
of blocks of code to convey program structure. This article largely addresses the
free-form language In computer programming, a free-form language is a programming language in which the positioning of characters on the page in program text is insignificant. Program text does not need to be placed in specific columns as on old punched card syst ...
s, such as C and its descendants, but can be (and often is) applied to most other
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s (especially those in the curly bracket family), where whitespace is otherwise insignificant. Indentation style is only one aspect of
programming style Programming style, also known as code style, is a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers read and understand sour ...
. Indentation is not a requirement of most programming languages, where it is used as secondary notation. Rather, indenting helps better convey the structure of a program to human readers. Especially, it is used to clarify the link between
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
constructs such as conditions or loops, and code contained within and outside of them. However, some languages (such as
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
and occam) use indentation to determine the structure instead of using braces or keywords; this is termed the
off-side rule A computer programming language is said to adhere to the off-side rule of syntax if blocks in that language are expressed by their indentation. The term was coined by Peter Landin, possibly as a pun on the offside rule in association football. ...
. In such languages, indentation is meaningful to the compiler or interpreter; it is more than only a clarity or style issue. This article uses the term
bracket A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
s to refer to
parentheses A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
, and the term braces to refer to curly brackets.


Brace placement in compound statements

The main difference between indentation styles lies in the placing of the braces of the compound statement () that often follows a control statement (if, while, for...). The table below shows this placement for the style of statements discussed in this article; function declaration style is another case. The style for brace placement in statements may differ from the style for brace placement of a function definition. For consistency, the indentation depth has been kept constant at 4 spaces, regardless of the preferred indentation depth of each style.


Tabs, spaces, and size of indentations

The displayed width for tabs can be set to arbitrary values in most programming editors, including
Notepad++ Notepad++ is a text and source code editor for use with Microsoft Windows. It supports tabbed editing, which allows working with multiple open files in a single window. The product's name comes from the C postfix increment operator. Notepad++ ...
(MS-Windows),
TextEdit TextEdit is an open-source word processor and text editor, first featured in NeXT's NeXTSTEP and OPENSTEP. It is now distributed with macOS since Apple Inc.'s acquisition of NeXT, and available as a GNUstep application for other Unix-like ope ...
(MacOS/X), Emacs (Unix), vi (Unix), and nano (Unix). In addition, these editors can be configured to generate a mix of tabs and spaces or to convert between tabs and spaces, to match specific indentation schemes. In Unix, the tab width can also be set in
pagers A pager (also known as a beeper or bleeper) is a wireless telecommunications device that receives and displays alphanumeric or voice messages. One-way pagers can only receive messages, while response pagers and two-way pagers can also acknow ...
, such as
less Less or LESS may refer to: fewer than,: not as much. Computing * less (Unix), a Unix utility program * Less (stylesheet language), a dynamic stylesheet language * Large-Scale Scrum (LeSS), a product development framework that extends Scrum Othe ...
, and converted on the fly by filters, such as expand/ unexpand.
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
editors default to positioning tabs at intervals of eight columns, while
Macintosh The Mac (known as Macintosh until 1999) is a family of personal computers designed and marketed by Apple Inc., Apple Inc. Macs are known for their ease of use and minimalist designs, and are popular among students, creative professionals, and ...
and
MS-Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for ser ...
environments defaulted to four columns. This difference causes source code misalignment, when indentation that mixes tabs and spaces is displayed under a configuration that displays tabs differently from the author's configuration. There is ongoing debate amongst programmers about the choice between hard tabs and spaces. Many early programmers used tab characters to indent, for ease of typing and to save on source file size. Some programmers, such as
Jamie Zawinski Jamie Zawinski (born November 3, 1968), commonly known as jwz, is an American computer programmer, blogger and impresario. He is best known for his role in the creation of Netscape Navigator, Netscape Mail, Lucid Emacs, Mozilla.org, and XScree ...
, state that using spaces instead of tabs increases
cross-platform In computing, cross-platform software (also called multi-platform software, platform-agnostic software, or platform-independent software) is computer software that is designed to work in several computing platforms. Some cross-platform software r ...
portability. Others, such as the writers of the
WordPress WordPress (WP or WordPress.org) is a free and open-source content management system (CMS) written in hypertext preprocessor language and paired with a MySQL or MariaDB database with supported HTTPS. Features include a plugin architecture ...
coding standards, state the opposite: that hard tabs increase portability. A survey of the top 400,000 repositories on
GitHub GitHub, Inc. () is an Internet hosting service for software development and version control using Git. It provides the distributed version control of Git plus access control, bug tracking, software feature requests, task management, continuous ...
found that spaces are more common. The size of the indentation is usually independent of the style. An experiment performed on PASCAL code in 1983, found that indentation size significantly affected comprehensibility. Indentation sizes between 2 and 4 characters proved optimal. For
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, many
shell script A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manip ...
ing languages, and some forms of
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScri ...
formatting, two spaces per indentation level is generally used.


Tools

There are many tools to convert between indentation styles, such as indent, a program included with many
Unix-like A Unix-like (sometimes referred to as UN*X or *nix) operating system is one that behaves in a manner similar to a Unix system, although not necessarily conforming to or being certified to any version of the Single UNIX Specification. A Unix-li ...
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
s. In
Emacs Emacs , originally named EMACS (an acronym for "Editor MACroS"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, s ...
, various commands are available to automatically fix indentation problems, including hitting Tab on a given line (in the default configuration). M-x indent-region can be used to properly indent large sections of code. Depending on the mode, Emacs can also replace leading indentation spaces with the proper number of tabs followed by spaces, which results in the minimal number of characters for indenting each source line.
Elastic tabstops A tab stop on a typewriter is a location where the carriage movement is halted by an adjustable end stop. Tab stops are set manually, and pressing the tab key causes the carriage to go to the next tab stop. In text editors on a computer, the same ...
is a tabulation style which requires support from the text editor, where entire blocks of text are kept automatically aligned when the length of one line in the block changes.


Styles


K&R style

The K&R style (Kernighan & Ritchie Style), and the closely related "one true brace style" in hacker jargon (abbreviated as 1TBS), are commonly used in C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, and other curly-brace programming languages. It was the style used in the original Unix kernel, Kernighan and Ritchie's book ''
The C Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as ...
'', as well as Kernighan and Plauger's book ''
The Elements of Programming Style ''The Elements of Programming Style'', by Brian W. Kernighan and P. J. Plauger, is a study of programming style, advocating the notion that computer programs should be written not only to satisfy the compiler or personal programming "style", bu ...
''. When following K&R, each function has its opening brace at the next line on the same indentation level as its header, the statements within the braces are indented, and the closing brace at the end is on the same indentation level as the header of the function at a line of its own. Multi-line blocks inside a function, however, have their opening braces at the same line as their respective control statements; closing braces remain in a line of their own, unless followed by a keyword else or while. Such non- aligned braces are nicknamed "Egyptian braces" (or "Egyptian brackets") for their resemblance to arms in some fanciful poses of ancient Egyptians. In K&R, single-line blocks do not have braces. int main(int argc, char *argv[]) ''The C Programming Language#Influence, The C Programming Language'' does not explicitly specify this style, though it is followed consistently throughout the book. From the book:
The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently.
In old versions of the C language, argument types needed to be declared on the subsequent line (i.e., just after the header of the function): /* Original pre-ISO C style without function prototypes */ int main(argc, argv) int argc; char *argv[];


Variant: 1TBS (OTBS)

The "one true brace style" (abbreviated as 1TBS or OTBS) is very similar to K&R. The main two differences are that functions have their opening braces on the same line separated by a space, and that the braces are not omitted for a control statement with only a single statement in its scope. In this style, the constructs that allow insertions of new code lines are on separate lines, and constructs that prohibit insertions are on one line. This principle is amplified by bracing every if, else, while, etc., including single-line conditionals, so that insertion of a new line of code anywhere is always safe (i.e., such an insertion will not make the flow of execution disagree with the source code indenting). Suggested advantages of this style are that the starting brace needs no extra line alone, and the ending brace lines up with the statement it conceptually belongs to. One cost of this style is that the ending brace of a block needs a full line alone, which can be partly resolved in if/else blocks and do/while blocks: void checknegative(x) There are many mentions of The One True Brace Style, but there is some confusion as to its true form. Some sources say that it is the variation specified above, while others note that it as just another "hacker jargon" term for K&R.


Variant: Linux kernel

A minor variant of the K&R style is the Linux kernel style, which is known for its extensive use in the source tree of the
Linux kernel The Linux kernel is a free and open-source, monolithic, modular, multitasking, Unix-like operating system kernel. It was originally authored in 1991 by Linus Torvalds for his i386-based PC, and it was soon adopted as the kernel for the GNU ope ...
.
Linus Torvalds Linus Benedict Torvalds ( , ; born 28 December 1969) is a Finnish software engineer who is the creator and, historically, the lead developer of the Linux kernel, used by Linux distributions and other operating systems such as Android. He also c ...
strongly advises all contributors to follow it. The style borrows many elements from K&R. The kernel style uses
tab stop A tab stop on a typewriter is a location where the carriage movement is halted by an adjustable end stop. Tab stops are set manually, and pressing the tab key causes the carriage to go to the next tab stop. In text editors on a computer, the sam ...
s (with the tab stops set every 8 characters) for indentation. Opening curly braces of a function go to the start of the line following the function header. Any other opening curly braces go on the same line as the corresponding statement, separated by a space. Labels in a switch statement are aligned with the enclosing block (there is only one level of indents). Line length used to be limited to 80 characters it was raised to 100 in 2020, but the original limit is still preferred. A single-statement body of a compound statement (such as if, while, and do-while) need not be surrounded by curly braces. If, however, one or more of the substatements in an if-else statement require braces, then both substatements should be wrapped inside curly braces: int power(int x, int y)


Variant: mandatory braces

Some advocate mandatory braces for control statements with only a single statement in its scope, i.e., bracing every if, else, while, etc., including single-line conditionals, so that insertion of a new line of code anywhere is always ''safe'' (i.e., such an insertion will not make the flow of execution disagree with the source-code indentation). The cost of this style is that one extra full line is needed for the last block (except for intermediate blocks in if/else if/else constructs and do/while blocks).


Variant: Java

While
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
is sometimes written in other styles, a significant body of Java code uses a minor variant of the
K&R style In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be (and often ...
in which the opening brace is on the same line not only for the blocks inside a function, but also for class or method declarations. This style is widespread largely because
Sun Microsystems Sun Microsystems, Inc. (Sun for short) was an American technology company that sold computers, computer components, software, and information technology services and created the Java programming language, the Solaris operating system, ZFS, the ...
's original style guides used this K&R variant, and as a result, most of the standard source code for the
Java API There are two types of Java programming language application programming interfaces (APIs): * The official core Java API, contained in the Android (Google), SE (OpenJDK and Oracle), MicroEJ. These packages (java.* packages) are the core Java la ...
is written in this style. It is also a popular indentation style for
ActionScript ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning i ...
and
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, along with the
Allman style In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be (and often ...
.


Variant: Stroustrup

Stroustrup style is
Bjarne Stroustrup Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University. ...
's adaptation of K&R style for C++, as used in his books, such as ''Programming: Principles and Practice using C++'' and ''
The C++ Programming Language ''The C++ Programming Language'' is a computer programming book first published in October 1985. It was the first book to describe the C++ programming language, written by the language's creator, Bjarne Stroustrup. In the absence of an official s ...
''. Unlike the variants above, Stroustrup does not use a "cuddled else". Thus, Stroustrup would write if (x < 0) else Stroustrup extends K&R style for classes, writing them as follows: class Vector ; Stroustrup does not indent the labels and . Also, in this style, while the opening brace of a ''function'' starts on a new line, the opening brace of a ''class'' is on the same line as the class name. Stroustrup allows writing short functions all on one line. Stroustrup style is a named indentation style available in the editor
Emacs Emacs , originally named EMACS (an acronym for "Editor MACroS"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, s ...
. Stroustrup encourages a K&R-derived style layout with C++ as stated in his modern ''C++ Core Guidelines''.


Variant: BSD KNF

Also termed
Kernel Normal Form Kernel normal form, or KNF, is the coding style used in the development of code for the BSD operating systems. Based on the original KNF concept from the Computer Systems Research Group, it dictates a programming style to which contributed code ...
, this is the form of most of the code used in the
Berkeley Software Distribution The Berkeley Software Distribution or Berkeley Standard Distribution (BSD) is a discontinued operating system based on Research Unix, developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berk ...
(BSD) operating systems. Although mostly intended for kernel code, it is also widely used in userland code. It is essentially a thoroughly documented variant of K&R style as used in the Bell Labs Version 6 & 7
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
source code. The SunOS kernel and userland uses a similar indentation style. Like KNF, this also was based on AT&T style documents and is sometimes termed Bill Joy Normal Form. The SunOS guideline was published in 1996; ANSI C is discussed briefly. The correctness of the indentation of a list of source files can be verified by the ''cstyle'' program written by Bill Shannon. In this style, the hard tabulator (ts in vi) is kept at eight columns, while a soft tabulator is often defined as a helper also (sw in vi), and set at four. The hard tabulators are used to indent code blocks, while a soft tabulator (four spaces) of additional indentation is used for all continuing lines that must be split over multiple lines. Moreover, function calls do not use a space before the parenthesis, although C-language native statements such as if, while, do, switch and return do (in the case where return is used with parens). Functions that declare no local variables in their top-level block should also leave an empty line after their opening block brace. Here follow a few samples: while (x

y) finalthing();
if (data != NULL && res > 0) else static JSBool pgresult_constructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)


Allman style

The Allman style is named after
Eric Allman Eric Paul Allman (born September 2, 1955) is an American computer programmer who developed sendmail and its precursor delivermail in the late 1970s and early 1980s at UC Berkeley. In 1998, Allman and Greg Olson co-founded the company Sendmail, I ...
. It is also sometimes termed ''BSD style'' since Allman wrote many of the utilities for
BSD The Berkeley Software Distribution or Berkeley Standard Distribution (BSD) is a discontinued operating system based on Research Unix, developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berk ...
Unix (although this should not be confused with the different "BSD KNF style"; see above). This style puts the brace associated with a control statement on the next line, indented to the same level as the control statement. Statements within the braces are indented to the next level. while (x

y) finalthing();
This style is similar to the standard indentation used by the Pascal languages and
Transact-SQL Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to the SQL (Structured Query Language) used to interact with relational databases. T-SQL expands on the SQL standard to include procedural programming, local variables, vari ...
, where the braces are equivalent to the keywords begin and end. (* Example Allman code indentation style in Pascal *) procedure dosomething(x, y: Integer); begin while x = y do begin something(); somethingelse(); end; end; Consequences of this style are that the indented code is clearly set apart from the containing statement by lines that are almost all whitespace and the closing brace lines up in the same column as the opening brace. Some people feel this makes it easy to find matching braces. The blocking style also delineates the block of code from the associated control statement. Commenting out or removing a control statement or block of code, or
code refactoring In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structur ...
, are all less likely to introduce syntax errors via dangling or missing braces. Also, it is consistent with brace placement for the outer-function block. For example, the following is still correct syntactically: // while (x

y)
As is this: // for (int i=0; i < x; i++) // while (x

y) if (x

y)
Even like this, with conditional compilation: int c; #ifdef HAS_GETCH while ((c = getch()) != EOF) #else while ((c = getchar()) != EOF) #endif


Variant: Allman-8

A popular variant for use in education, Allman-8 uses the 8-space indentation tabs and 80-column limit of the Linux Kernel variant of K&R. The style purportedly helps improve readability on projectors. Also, the indentation size and column restriction help create a visual cue for identifying excessive nesting of code blocks. These advantages combine to help provide newer developers and learners implicit guidance to manage code complexity.


Whitesmiths style

The Whitesmiths style, also sometimes termed Wishart style, was originally used in the documentation for the first commercial C compiler, the
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C c ...
Compiler. It was also popular in the early days of Windows, since it was used in three influential Windows programming books, '' Programmer's Guide to Windows'' by Durant, Carlson & Yao, '' Programming Windows'' by Petzold, and ''
Windows 3.0 Power Programming Techniques Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for ser ...
'' by
Norton Norton may refer to: Places Norton, meaning 'north settlement' in Old English, is a common place name. Places named Norton include: Canada * Rural Municipality of Norton No. 69, Saskatchewan *Norton Parish, New Brunswick **Norton, New Brunswick, a ...
& Yao. Whitesmiths, along with Allman, have been the most common bracing styles with equal popularity according to the
Jargon File The Jargon File is a glossary and usage dictionary of slang used by computer programmers. The original Jargon File was a collection of terms from technical cultures such as the MIT AI Lab, the Stanford AI Lab (SAIL) and others of the old ARPANET A ...
. This style puts the brace associated with a control statement on the next line, indented. Statements within the braces are indented to the same level as the braces. Like Ratliff style, the closing brace is indented the same as statements within the braces. while (x

y) finalthing();
The advantages of this style are similar to those of the
Allman style In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be (and often ...
. Blocks are clearly set apart from control statements. The alignment of the braces with the block emphasizes that the full block is conceptually, and programmatically, one compound statement. Indenting the braces emphasizes that they are subordinate to the control statement. The ending brace no longer lines up with the statement, but instead with the opening brace. An example: if (data != NULL && res > 0) else if (!JS_DefineProperty(cx, o, "data", OBJECT_TO_JSVAL(NULL), NULL, NULL, JSPROP_ENUMERATE)) else if are treated as statement, much like the #elif preprocessor statement.


GNU style

Like the Allman and
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C c ...
styles,
GNU GNU () is an extensive collection of free software (383 packages as of January 2022), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operat ...
style puts braces on a line by themselves, indented by two spaces, except when opening a function definition, where they are not indented. In either case, the contained code is indented by two spaces from the braces. Popularised by
Richard Stallman Richard Matthew Stallman (; born March 16, 1953), also known by his initials, rms, is an American free software movement activist and programmer. He campaigns for software to be distributed in such a manner that its users have the freedom to ...
, the layout may be influenced by his background of writing
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
code. In Lisp, the equivalent to a block (a progn) is a first-class data entity, and giving it its own indentation level helps to emphasize that, whereas in C, a block is only syntax. This style can also be found in some
ALGOL ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
and
XPL XPL is a programming language based on PL/I, a portable one-pass compiler written in its own language, and a parser generator tool for easily implementing similar compilers for other languages. XPL was designed in 1967 as a way to teach compiler d ...
programming language textbooks from the 1960s and 1970s. Although not directly related to indentation, GNU coding style also includes a space before the bracketed list of arguments to a function. static char * concat (char *s1, char *s2) This style combines the advantages of Allman and
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C c ...
, thereby removing the possible Whitesmiths disadvantage of braces not standing out from the block. One disadvantage is that the ending brace no longer lines up with the statement it conceptually belongs to. Another possible disadvantage is that it might waste space by using two visual levels of indents for one conceptual level, but in reality this is unlikely because, in systems with single-level indentation, each level is usually at least 4 spaces, same as 2 * 2 spaces in GNU style. The GNU Coding Standards recommend this style, and nearly all maintainers of
GNU project The GNU Project () is a free software, mass collaboration project announced by Richard Stallman on September 27, 1983. Its goal is to give computer users freedom and control in their use of their computers and computing devices by collaborati ...
software use it. The
GNU Emacs GNU Emacs is a free software text editor. It was created by GNU Project founder Richard Stallman, based on the Emacs editor developed for Unix operating systems. GNU Emacs has been a central component of the GNU project and a flagship project of ...
text editor and the GNU systems' indent command will reformat code according to this style by default. Those who do not use GNU Emacs, or similarly extensible/customisable editors, may find that the automatic indentation settings of their editor are unhelpful for this style. However, many editors defaulting to KNF style cope well with the GNU style when the tab width is set to two spaces; likewise, GNU Emacs adapts well to KNF style by simply setting the tab width to eight spaces. In both cases, automatic reformatting destroys the original spacing, but automatic line indenting will work properly. Steve McConnell, in his book
Code Complete ''Code Complete'' is a software development book, written by Steve McConnell and published in 1993 by Microsoft Press, encouraging developers to continue past code-and-fix programming and the big design up front and waterfall models. It is ...
, advises against using this style: he marks a code sample which uses it with a "Coding Horror" icon, symbolizing especially dangerous code, and states that it impedes readability. The
Linux kernel The Linux kernel is a free and open-source, monolithic, modular, multitasking, Unix-like operating system kernel. It was originally authored in 1991 by Linus Torvalds for his i386-based PC, and it was soon adopted as the kernel for the GNU ope ...
coding style documentation also strongly recommends against this style, urging readers to burn a copy of the GNU coding standards as a "great symbolic gesture".


Horstmann style

The 1997 edition of ''Computing Concepts with C++ Essentials'' by Cay S. Horstmann adapts Allman by placing the first statement of a block on the same line as the opening brace. This style is also used in examples in Jensen and Wirth's ''Pascal User Manual and Report''. while (x

y) finalthing();
This style combines the advantages of Allman by keeping the vertical alignment of the braces for readability, and identifying blocks easily, with the saving of a line of the K&R style. However, the 2003 edition now uses Allman style throughout.


Pico style

This is the style used most commonly in the language
Pico Pico may refer to: Places The Moon * Mons Pico, a lunar mountain in the northern part of the Mare Imbrium basin Portugal * Pico, a civil parish in the municipality of Vila Verde * Pico da Pedra, a civil parish in the municipality of Ribeir ...
by its designers. Pico lacks return statements, and uses semicolons as statement separators instead of terminators. It yields this syntax:
stuff(n):

The advantages and disadvantages are similar to those of saving screen real estate with K&R style. An added advantage is that the starting and closing braces are consistent in application (both share space with a line of code), relative to K&R style, where one brace shares space with a line of code and one brace has a line alone.


Ratliff style

In the book ''Programmers at Work'', C. Wayne Ratliff discussed using the style below. The style begins much like 1TBS but then the closing brace lines up with the indentation of the nested block. Ratliff was the original programmer behind the popular dBase-II and -III
fourth-generation programming language A fourth-generation programming language (4GL) is any computer programming language that belongs to a class of languages envisioned as an advancement upon third-generation programming languages (3GL). Each of the programming language generations a ...
s. He indicated that it was originally documented in material from
Digital Research Digital Research, Inc. (DR or DRI) was a company created by Gary Kildall to market and develop his CP/M operating system and related 8-bit, 16-bit and 32-bit systems like MP/M, Concurrent DOS, FlexOS, Multiuser DOS, DOS Plus, DR DOS and ...
Inc. This style has sometimes been termed ''banner'' style, possibly for the resemblance to a banner hanging from a pole. In this style, which is to
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C c ...
as K&R is to Allman, the closing control is indented the same as the last item in the list (and thus properly loses salience) The style can make visual scanning easier for some, since the ''headers'' of any block are the only thing exdented at that level (the theory being that the closing control of the prior block interferes with the visual flow of the next block header in the K&R and Allman styles). Kernighan and Plauger use this style in the Ratfor code in ''Software Tools''. // In C for (i = 0; i < 10; i++) or, in a markup language...


Lisp style

A programmer may even go as far as to insert closing braces in the last line of a block. This style makes indentation the only way to distinguish blocks of code, but has the advantage of containing no uninformative lines. This could easily be called the Lisp style (because this style is very common in Lisp code) or the Python style (Python has no braces, but the layout is very similar, as shown in the code blocks below). In Python, layout is a part of the language, called the
off-side rule A computer programming language is said to adhere to the off-side rule of syntax if blocks in that language are expressed by their indentation. The term was coined by Peter Landin, possibly as a pun on the offside rule in association football. ...
. // In C for (i = 0; i < 10; i++)   # In Python for i in range(10): if i % 2

0: do_something(i) else: do_something_else(i) do_third_thing(i)
  ;; In Lisp (dotimes (i 10) (if (= (rem i 2) 0) (do-something i) (progn (do-something-else i) (do-third-thing i))))


Haskell style

Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
layout can make the placement of braces optional, although braces and semicolons are allowed in the language. The two segments below are equally acceptable to the compiler: braceless = do text <- getContents let firstWord = head $ words text bigWord = map toUpper firstWord putStrLn bigWord braceful = do In Haskell, layout can replace braces. Usually the braces and semicolons are omitted for procedural do sections and the program text in general, but the style is commonly used for lists, records and other syntactic elements made up of some pair of parentheses or braces, which are separated with commas or semicolons. If code following the keywords where, let, or of omits braces and semicolons, then indentation is significant.


APL style

For an example of how terse APL typically is, here is the implementation of the step function for the Game of Life: life← APL style C resembles the terse style of APL code, and is commonly used in their implementations. This style was pioneered by Arthur Whitney, and is heavily used in the implementation of K, Arthur's own project. The J programming language is implemented in this style as well. Notably, not all implementations of APL use this style of C, namely: GNU APL and Dyalog APL. In addition to APL style C indentation, typically the names are shortened to either single or double characters: To reduce the amount of indentation, and expressions spanning multiple lines.


Other considerations


Losing track of blocks

In some situations, there is a risk of losing track of block boundaries. This is often seen in large sections of code containing many compound statements nested to many levels of indentations. By the time the programmer scrolls to the bottom of a huge set of nested statements, they may have lost track of which control statements go where. However, overly-long code could have other causes, such as being too
complex Complex commonly refers to: * Complexity, the behaviour of a system whose components interact in multiple ways so possible interactions are difficult to describe ** Complex system, a system composed of many components which may interact with each ...
, and a programmer facing this problem might instead consider whether
code refactoring In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structur ...
would help in the longer term. Programmers who rely on counting the opening braces may have difficulty with indentation styles such as K&R, where the starting brace is not visually separated from its control statement. Programmers who rely more on indentations will gain more from styles that are vertically compact, such as K&R, because the blocks are shorter. To avoid losing track of control statements such as for, a large indentation can be used, such as an 8-unit-wide hard tab, along with breaking up large functions into smaller and more readable functions. Linux is done this way, while using the K&R style. In text editors of the vi family, one means to track block boundaries is to position the text cursor over one of the braces, and press the % key. The cursor then jumps to the opposing brace. Since the text cursor's next key (viz., the n key) retained directional positioning information (whether the up or down key was formerly pressed), the dot macro (the . key) could then be used to place the text cursor on the next brace, given a suitable coding style. Instead, inspecting the block boundaries using the % key can be used to enforce a coding standard. Another way is to use inline comments added after the closing brace: for (int i = 0; i < total; i++) //for (i) if (x < 0) //if (x < 0) The major disadvantage of this method is maintaining duplicate code in multiple locations. Another solution is implemented in a
folding editor Code or text folding, or less commonly holophrasting, is a feature of some graphical user interfaces that allows the user to selectively hide ("fold") or display ("unfold") parts of a document. This allows the user to manage large amounts of text ...
, which can hide or reveal blocks of code via their indentation level or compound-statement structure. Many editors will also highlight matching brackets or braces when the
cursor Cursor may refer to: * Cursor (user interface), an indicator used to show the current position for user interaction on a computer monitor or other display device * Cursor (databases), a control structure that enables traversal over the records in ...
is positioned next to one.


Statement insertion

K&R style prevents another common error suffered when using the standard
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
line editor, ed. A statement mistakenly inserted between the control statement and the opening brace of the loop block turns the body of the loop into a single trip. for (int i = 0; i < 10; i++) whoops(bar); /* repeated 10 times, with i from 0 to 9 */ //for (i) ← This comment is no longer valid, and is very misleading! K&R style avoids this problem by keeping the control statement and the opening brace on the same line.


See also

* Secondary notation *
Syntax highlighting Syntax highlighting is a feature of text editors that are used for programming, scripting, or markup languages, such as HTML. The feature displays text, especially source code, in different colours and fonts according to the category of terms ...
* Indentation in programming


References


External links


''C Style: Standards and Guidelines: Defining Programming Standards for Professional C Programmers''
Prentice Hall, / (full text is also online). Straker, David (1992).



*


Tabs and spaces



by Jamie Zawinski

by Adam Spiers

(archived)
''Elastic tabstops – the solution to the tabs-versus-spaces issue''
{{DEFAULTSORT:Indent Style Software wars Text editor features Source code